package red.yancloud.www.base


import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import red.yancloud.www.R
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.TimeFormatUtil
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.UrlUtils
import java.text.SimpleDateFormat
import java.util.*


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/13 17:23
 * E_Mail：yh131412hys@163.com
 * Describe：基类BaseWebViewFragment
 * Change：
 * @Version：V1.0
 */
abstract class BaseWebViewFragment : BaseFragment() {

    private val TAG = "BaseWebViewFragment"

    protected lateinit var mWebView: WebView
    protected lateinit var mRefreshLayout: SmartRefreshLayout
    private lateinit var errorLayout: LinearLayoutCompat
    private lateinit var errorTv: AppCompatTextView
    protected lateinit var mHandler: Handler
    protected lateinit var mUrl: String

//    override fun getLayoutResId(): Int {
//        return R.layout.fragment_base_web_view
//    }

    override fun attachView() {
    }

    override fun initData() {

    }

    override fun configView() {

        mWebView = parentView.findViewById<WebView>(R.id.webViewFragment_webView)
        mRefreshLayout = parentView.findViewById<SmartRefreshLayout>(R.id.webViewFragment_refreshLayout)
        errorLayout = parentView.findViewById<LinearLayoutCompat>(R.id.webViewFragment_errorView)
        errorTv = parentView.findViewById<AppCompatTextView>(R.id.empty_view_tv)
        errorLayout.findViewById<View>(R.id.reload).setOnClickListener(View.OnClickListener {
            if (!NetworkUtils.isConnected(mContext)) {
                errorLayout.visibility = View.VISIBLE
                errorTv.setText(R.string.no_network_view_hint)
                ToastUtils.toastNetErrorMsg()
                return@OnClickListener
            }
            loadWeb()
        })

        initSmartRefreshLayout()

        mHandler = Handler()
        webSetting()
        mWebView.webViewClient = MyWebViewClient()
        mWebView.webChromeClient = MyChromeClient()

        if (!NetworkUtils.isConnected(mContext)) {
            errorLayout.visibility = View.VISIBLE
            errorTv.setText(R.string.no_network_view_hint)
            ToastUtils.toastNetErrorMsg()
            return
        }
        loadWeb()
    }

    private fun initSmartRefreshLayout() {

        val delta = Random().nextInt(7 * 24 * 60 * 60 * 1000)
        val mClassicsHeader = mRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis() /*- delta*/))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

        mRefreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(Runnable {

                //                mAdapter.refresh(initData());
//                refreshLayout.finishRefresh();
//                refreshLayout.resetNoMoreData();//setNoMoreData(false);

                if (!NetworkUtils.isConnected(mContext)) {
                    errorLayout.visibility = View.VISIBLE
                    errorTv.setText(R.string.no_network_view_hint)
                    ToastUtils.toastNetErrorMsg()
                    mRefreshLayout.finishRefresh()
                    return@Runnable
                }
                loadWeb()
            }, 1000)
        }
    }

    private fun loadWeb() {

        if (!(mContext as Activity).isFinishing) {
            loadingDialog.show()
        }

        Log.d(TAG, "loadWeb: " + UrlUtils.markSignUrl(mUrl))
        mWebView.loadUrl(/*UrlUtils.markSignUrl(mUrl)*/mUrl)
    }

    /**
     * 网页配置参数设置
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun webSetting() {

        mWebView.isFocusable = true
        mWebView.setBackgroundColor(0x00ffffff)
        mWebView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY

        /*webView.setHorizontalScrollBarEnabled(false);//水平不显示
webView.setVerticalScrollBarEnabled(false); //垂直不显示
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);//滚动条在WebView内侧显示
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY)//滚动条在WebView外侧显示*/

        val webSetting: WebSettings = mWebView.settings
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
//        }
        webSetting.javaScriptCanOpenWindowsAutomatically = true
        webSetting.javaScriptEnabled = true
        //允许混合加载
        webSetting.setAllowUniversalAccessFromFileURLs(true)
        webSetting.setAppCacheEnabled(false)
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE

        addJavaScriptInterface()
    }

    abstract fun addJavaScriptInterface()

    /**
     * @Author：风不会停息 on 2019/2/15 11:48
     * E_Mail：yh131412hys@163.com
     * @Description：监听网页状态
     * @Change：
     * @Version：V1.0
     */
    private inner class MyWebViewClient : WebViewClient() {

        //        @Override
        //        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        //            String url = request.getUrl().toString();
        //            view.loadUrl(url);
        //            return super.shouldOverrideUrlLoading(view, request);
        //        }
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            Log.d(TAG, "shouldOverrideUrlLoading: $url")
            view.loadUrl(url)
            return true
        }

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            Log.d(TAG, "onPageStarted: $url")

//            if (!(mContext as Activity).isFinishing) {
//                loadingDialog.show()
//            }
        }

        override fun onPageFinished(view: WebView, url: String) {

            if (NetworkUtils.isConnected(mContext)) {

                errorLayout.visibility = View.GONE
            } else {

                errorLayout.visibility = View.VISIBLE
                errorTv.setText(R.string.no_network_view_hint)
                ToastUtils.toastNetErrorMsg()
            }
            if (null == mWebView.title) {
                return
            }

            Log.d(TAG, "onPageFinished: " + mWebView.title)
//            if ("" != mWebView.title && mWebView.title.length > 20) {
//                title.text = ""
//            }else{
//                title.text = mWebView.title
//            }
            mRefreshLayout.finishRefresh()
            if (!(mContext as Activity).isFinishing) {
                loadingDialog.dismiss()
            }
        }

        //        @Override
        //        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        //            super.onReceivedError(view, request, error);
        //            webView.loadUrl("file:///android_asset/repair/repair.html");
        //            webView.getSettings().setLayoutAlgorithm( WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //
        //            title.setText("获取失败");
        //
        //            if (null != loadingDialog && !isFinishing()) {
        //                LoadingDialog.cancel();
        //                loadingDialog = null;
        //            }
        //        }

        override fun onReceivedError(
            view: WebView, errorCode: Int,
            description: String, failingUrl: String) {
            super.onReceivedError(view, errorCode, description, failingUrl)

            //            webView.loadUrl("file:///android_asset/repair/repair.html");
            //            webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

//            title.text = "获取失败"

            if (!(mContext as Activity).isFinishing) {
                loadingDialog.dismiss()
            }
        }

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, p2: SslError?) {

            Log.d(TAG, "onReceivedSslError: ")
            handler!!.proceed()
        }
    }

    /**
     * @Author：风不会停息 on 2019/2/15 11:47
     * E_Mail：yh131412hys@163.com
     * @Description：监听网页加载进度
     * @Change：
     * @Version：V1.0
     */
    private inner class MyChromeClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            //            progressBar.setProgress(newProgress);
            //            progressBar.postInvalidate();
        }

        override fun onCreateWindow(
            view: WebView, isDialog: Boolean,
            isUserGesture: Boolean, resultMsg: Message
        ): Boolean {
            return super.onCreateWindow(
                view, isDialog, isUserGesture,
                resultMsg
            )
        }

        override fun onCloseWindow(window: WebView) {
            super.onCloseWindow(window)
        }
    }
}
